import Taro from '@tarojs/taro'

const LOCAL_AREA_KEY = 'local_area_key';

// 我想进入全局的时候 就应该读取全局常量、配置

// 获取数据合集
export const getAreas = async ({ hasEmpty = true } = {}) => {
  let areaStr = '';
	try {
		areaStr = Taro.getStorageSync(LOCAL_AREA_KEY);
	} catch (e) {
		areaStr = ''
	}
  let areas = [];
  if (areaStr) {
    console.log('从localstrong中取数据：')
    areas = JSON.parse(areaStr)
  } else {
		const areasData = await Taro.request({
      method: 'POST',
      url: '/api/district',
      data: {}
    })
    areas = areasData.data;
		try {
			Taro.setStorageSync(LOCAL_AREA_KEY, JSON.stringify(areas));
		} catch (e) { 
			console.log('设置地址存储失败：', e)
		}
  }

  if (hasEmpty) {
    formatEmpty(areas);
  }

  console.log('从接口取数据:');
  return areas;
}

export const formatEmpty = (list, level = 0) => {
  if (level === 0) {
    list.unshift({
      name: '全国',
    })
  } else {
    list.unshift({
      name: '不限',
    })
  }

  list.forEach(item => {
    if (!item.children && level < 2) {
      item.children = []
    }
    if (level < 2) {
      formatEmpty(item.children, level + 1)
    }
  })
} 

// 获取省市区
export const getAreaRange = async ({ value, hasEmpty }) => {
  const [provinceIndex = 0, cityIndex = 0, regionIndex = 0] = value || [];
  const areas = await getAreas({ hasEmpty });
  const provinceNames = areas.map(item => {
    return item.name
  })

  const citys = areas?.[provinceIndex]?.children || [];
  const cityNames= citys.map(item => item.name);
  
  const regions = citys?.[cityIndex]?.children || []
  const regionNames = regions.map(item => item.name)

  const provinceName = provinceNames[provinceIndex] == '全国' ? '' : provinceNames[provinceIndex];
  const cityName = cityNames[cityIndex] == '不限' ? '' : cityNames[cityIndex]
  const regionName = regionNames[regionIndex] == '不限' ? '' : regionNames[regionIndex]

  return {
    ranges: [provinceNames, cityNames, regionNames],
    value: [provinceName, cityName, regionName]
  }
}

// 通过名称获取索引
export const getAreaIndexByNames = async ({
  names = [],
  hasEmpty
}) => {
  const areas = await getAreas({ hasEmpty });
  const [provinceName, cityName, regionName] = names || []
  
  let provinceIndex = areas.findIndex(item => item.name == provinceName);
  provinceIndex = provinceIndex === -1 ? 0 : provinceIndex;

  const citys = areas?.[provinceIndex]?.children || [];
  let cityIndex = citys.findIndex(item => item.name == cityName);
  cityIndex = cityIndex === -1 ? 0 : cityIndex;

  const regions = citys?.[cityIndex]?.children || []
  let regionIndex = regions.findIndex(item => item.name == regionName);
  regionIndex = regionIndex === -1 ? 0 : regionIndex;

  return [provinceIndex, cityIndex, regionIndex]
}